import json
from typing import List

from config.env_config import env_config
from utils.http import pms_http, tdp_http, trade_http, pomodel_http


class PmsApi:
    @staticmethod
    def policy_list(data, token):
        """查询策略列表"""
        url = "/api/policy/list"
        response = pms_http.get(url=url, data=data, token=token)
        return response

    @staticmethod
    def noauth_api_login(data):
        url = "/noauth/api/login"
        response = pms_http.post(url=url, data=data)
        return response

    @staticmethod
    def poRiskReflash(poCode):
        '''刷新组合风控信息'''
        url = "/internal/poRisk"
        data = {
            "poCode": poCode
        }
        response = pms_http.get(url=url, data=data)
        return response

    @staticmethod
    def stRiskReflash(strategyCode):
        '''刷新策略风控信息'''
        url = "/internal/stRisk"
        data = {
            "strategyCode": strategyCode
        }
        response = pms_http.get(url=url, data=data)
        return response

    @staticmethod
    def reflashPmsCache():
        '''刷新pms的全部缓存'''
        url = "/internal/flushCache"
        response = pms_http.get(url=url)
        return response

    @staticmethod
    def get_dict_data(token):
        """获取PMS字典"""
        url = "/api/system/dictData"
        response = pms_http.get(url=url, token=token)
        return response


class TdpApi:
    @staticmethod
    def manyStartOfPoCmd(prod_code, audit_type):
        '''当日多次可调仓发车
        param: audit_type 审核单类型，normal_adjust 普通调仓；normal_signal 普通发车；calendar_signal 广发定投家发车单；calendar_adjust 广发定投家调仓单；rgb 择时信号
        '''
        data = {
            "prod_code": prod_code,
            "audit_type": audit_type
        }
        tdp_http.postCmd(cmd="manyStartOfPoCmd", data=data)

    @staticmethod
    def reflashTradeCache():
        """刷新trade缓存"""
        tdp_http.postCmd(cmd="reflashTradeCache")

    @staticmethod
    def create_classic_po(userAccount, data={}):
        """单独创建经典组合"""
        data = {
            "userAccount": userAccount,
            "data": data
        }
        result = tdp_http.postCmd(cmd="createPoByPomodelCmd", data=data)["data"]
        return result

    @staticmethod
    def create_signal_po(userAccount, data={}):
        """单独创建信号组合"""
        data = {
            "userAccount": userAccount,
            "data": data
        }
        result = tdp_http.postCmd(cmd="createSignalByPomodelCmd", data=data)["data"]["info"]
        return result

    @staticmethod
    def clear_cma_and_relate_aap(cmdId, env=env_config.env):
        '''删除cma和关联的aap'''
        data = {
            "cmaId": cmdId
        }
        result = tdp_http.postCmd(cmd="clearCmaAndRelateAap", data=data, env=env)
        return result

    @staticmethod
    def clear_aap(aapIdList, env=env_config.env):
        '''单独删除aap'''
        aapIdListStr = ""
        for item in aapIdList:
            if aapIdListStr == "":
                aapIdListStr = item
            else:
                aapIdListStr = '%s,%s' % (aapIdListStr, item)
        data = {
            "aapIdList": aapIdListStr
        }
        result = tdp_http.postCmd(cmd="clearAap", data=data, env=env)
        return result

    @staticmethod
    def clear_policy(policy_list, env=env_config.env):
        """删除策略数据，如果策略关联组合，只删除关联关系，不删除组合"""
        policy_list_str = ','.join(policy_list)
        data = {
            "policy_list": policy_list_str
        }
        result = tdp_http.postCmd(cmd="clear_policy", data=data, env=env)
        return result

    @staticmethod
    def clearPoData(poCodeList, env=env_config.env):
        """删除组合数据"""
        poCodeListStr = ','.join(poCodeList)
        data = {
            "poCodeList": poCodeListStr
        }
        result = tdp_http.postCmd(cmd="clearPoData", data=data, env=env)
        return result

    @staticmethod
    def change_prod_risk(prod_code, prod_type="po", risk="R1-0", env=env_config.env):
        """修改产品风险等级"""
        data = {
            "prod_code": prod_code,
            "prod_type": prod_type,
            "risk": risk
        }
        result = tdp_http.postCmd(cmd="change_prod_risk", data=data, env=env)
        return result

    @staticmethod
    def change_po_composition(po_code, fund_code_list: List, env=env_config.env):
        """修改组合成分基金"""
        data = {
            "poCode": po_code,
            "fundCodeList": json.dumps(fund_code_list)
        }
        result = tdp_http.postCmd(cmd="changePoComposition", data=data, env=env)
        return result

    @staticmethod
    def add_policy_asset_pool(policy_code, fund_list=None, po_list=None, funds_by_po_list=None, env=env_config.env):
        """添加指定基金/组合到策略基金池"""
        data = {
            "strategyCode": policy_code,
            "ifAddGradeFund": "True",
            "ifOverWrite": "False"
        }
        if fund_list is not None:
            data["fundList"] = fund_list
        if po_list is not None:
            data["poList"] = po_list
        if funds_by_po_list is not None:
            data["fundsByPoList"] = funds_by_po_list
        result = tdp_http.postCmd(cmd="addPolicyAssetPool", data=data, env=env)
        return result


class TradeApi:
    @staticmethod
    def getTxnDay(offset=0, date=None):
        """获取交易日 offset = 0 代表当前交易日，-1 上一个交易日 1 下个交易日"""
        url = "/txnDay/getTxnDayForCount"
        reqDate = date
        if date is None:
            # reqDate = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
            reqDate = Tools.get_Beijing_now_date()
        data = {
            "date": reqDate,
            "n": offset
        }
        resp = trade_http.post(url=url, data=data)
        return resp['txnDay'].split(' ')[0]


class PomodelApi:
    @staticmethod
    def reflashPomodelCache():
        """清除pomodel缓存"""
        url = "/model/refreshCache"
        resp = pomodel_http.get(url=url)
        return resp
